﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;

namespace HttpClient
{
    /// <summary>  
    /// 有关HTTP请求的辅助类  
    /// </summary>  
    public class HttpClient
    {

        /// <summary>
        /// 通过GET方法获取Http内容
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>返回的HTML内容</returns>
        public static string GetHttpContent(string url, Encoding encoding) {
            string html = "";
            if (!String.IsNullOrWhiteSpace(url))
            {
                try
                {
                    WebClient MyWebClient = new WebClient();
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                    Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                    html = encoding.GetString(pageData);
                }
                catch
                {
                }
            }
            return html;
        }

        /// <summary>
        /// 通过Post方法获取Http内容
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="postData">Post数据</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>返回的HTML内容</returns>
        public static string GetHttpContentByPost(string url, string postData, Encoding encoding)
        {
            string html = "";
            if (!String.IsNullOrWhiteSpace(url))
            {
                try
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                    webRequest.Method = "post";
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    webRequest.ContentLength = byteArray.Length;
                    System.IO.Stream newStream = webRequest.GetRequestStream();
                    newStream.Write(byteArray, 0, byteArray.Length);
                    newStream.Close();
                    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                    html = new System.IO.StreamReader(response.GetResponseStream(), encoding).ReadToEnd();
                }
                catch
                {
                }
            }
            return html;
        }
    }
}